import type { RouteRecordRaw } from 'vue-router'
import { omit } from 'lodash'
import { basicRouteMap, getRouterModule } from './router-modules'
import type { MenuData, MenuDataItem } from '~@/layouts/basic-layout/typing'
import dynamicRoutes from '~@/router/dynamic-routes'
import { ROOT_ROUTE_REDIRECT_PATH } from '~@/router/constant'
import { i18n } from '~@/locales'
import type { MenuInfo, MenuItem } from '~@/api/portal'
import { randomString } from '~@/utils/tools'

export function i18nTitle(item: MenuItem) {
    const { text, i18n: locale } = item || {}
    if (!text)
        return ''
    return locale ? (i18n.global as any).t(locale) : text
}

export function convertMenu(item: MenuItem) {
    let icon = ''
    if (item.icon) {
        icon = item.icon.value.replace(/^./, item.icon.value[0].toUpperCase())
            + item.icon.theme.replace(/^./, item.icon.theme[0].toUpperCase())
    }
    return {
        id: item.id,
        parentId: item.parentId,
        title: () => i18nTitle(item),
        icon,
        path: item.link,
        hideInMenu: item.hide || false,
        parentKeys: [],
        hideInBreadcrumb: item.hideInBreadcrumb || false,
        hideChildrenInMenu: false,
        locale: item.i18n,
        keepAlive: item.open,
        name: item.key,
        url: item.externalLink || '',
        target: item.target || '_blank',
    }
}

export function getMenuData(menuInfo: MenuInfo) {
    const menuData: MenuData = []
    const { hasAccess } = useAccess()
    menuInfo.forEach((route) => {
        if (route.acl) {
            const isAccess = hasAccess(route.acl)
            if (!isAccess)
                return
        }
        const item: MenuDataItem = convertMenu(route)
        item.children = []
        if (route.children && route.children.length)
            item.children = getMenuData(route.children)
        if (item.children?.length === 0)
            delete item.children
        menuData.push(item)
    })
    return menuData
}

/**
 * 通过前端数据中的dynamic-routes动态生成菜单和数据
 */

export async function generateRoutes(menuInfo: MenuInfo) {
    const level0 = randomString(16)
    const level1 = randomString(16)
    const dashboard: MenuItem = {
        id: level0,
        text: '主导航',
        group: true,
        icon: {
            theme: 'outlined',
            value: 'dashboard',
        },
        hideInBreadcrumb: true,
        key: 'Dashboard',
        parentId: '0',
        title: '主导航',
        hide: false,
        link: '',
        children: [
            {
                id: randomString(32),
                text: '工作台',
                link: '/dashboard/workplace',
                key: 'DashboardWorkplace',
                parentId: level1,
                title: '工作台',
                hide: false,
                hideInBreadcrumb: false,
            },
        ],
    }
    const level3 = randomString(16)
    const level4_1 = randomString(16)
    const level4_2 = randomString(16)
    const profile: MenuItem = {
        id: level3,
        link: '/account',
        key: 'Account',
        text: '个人中心',
        title: '个人中心',
        parentId: '0',
        group: true,
        hide: false,
        hideInBreadcrumb: false,
        icon: { value: 'user', theme: 'outlined' },
        children: [
            {
                id: level4_1,
                link: '/account/center',
                key: 'AccountCenter',
                text: '个人主页',
                title: '个人主页',
                parentId: level3,
                group: true,
                hide: false,
                hideInBreadcrumb: false,
            },
            {
                id: level4_2,
                link: '/account/settings',
                key: 'AccountSettings',
                text: '个人设置',
                title: '个人设置',
                parentId: level3,
                group: false,
                hide: false,
                hideInBreadcrumb: false,
            },
        ],
    }
    const fullMenu = [dashboard].concat(menuInfo).concat(profile)
    const menuData = getMenuData(fullMenu)
    console.log(menuData)
    return {
        menuData,
        routeData: dynamicRoutes,
    }
}

function checkComponent(component: RouteRecordRaw['component']) {
    for (const componentKey in basicRouteMap) {
        if (component === (basicRouteMap as any)[componentKey])
            return undefined
    }
    return component
}

// 路由拉平处理
function flatRoutes(routes: RouteRecordRaw[], parentName?: string, parentComps: RouteRecordRaw['component'][] = []) {
    const flatRouteData: RouteRecordRaw[] = []
    for (const route of routes) {
        const parentComponents = [...parentComps]
        const currentRoute = omit(route, ['children']) as RouteRecordRaw
        if (!currentRoute.meta)
            currentRoute.meta = {}
        if (parentName)
            currentRoute.meta.parentName = parentName
        if (parentComponents.length > 0)
            currentRoute.meta.parentComps = parentComponents
        currentRoute.meta.originPath = currentRoute.path
        flatRouteData.push(currentRoute)
        if (route.children && route.children.length) {
            const comp = checkComponent(route.component)
            if (comp)
                parentComponents.push(comp)
            flatRouteData.push(...flatRoutes(route.children, route.name as string, [...parentComponents]))
        }
    }
    return flatRouteData
}

export function generateFlatRoutes(routes: RouteRecordRaw[]) {
    const flatRoutesList = flatRoutes(routes)
    // 拿到拉平后的路由，然后统一添加一个父级的路由,通过这层路由实现保活的功能
    const parentRoute: RouteRecordRaw = {
        path: '/',
        redirect: ROOT_ROUTE_REDIRECT_PATH,
        name: 'ROOT_EMPTY_PATH',
        component: getRouterModule('RouteView'),
        children: flatRoutesList,
    }
    return [parentRoute]
}
